package com.bootlever.framework.rmi.listener;

import com.bootlever.framework.rmi.annotation.RmiInject;
import com.bootlever.framework.rmi.annotation.RmiServer;
import com.bootlever.framework.rmi.bean.BootleverRmiContainer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;

import java.lang.reflect.Field;
import java.util.Iterator;

public class RmiInjectListener implements ApplicationListener<ContextRefreshedEvent> , BeanFactoryAware{

    private static final Logger logger = LoggerFactory.getLogger(RmiInjectListener.class);

    private DefaultListableBeanFactory beanFactory;

    @Autowired
    private BootleverRmiContainer container;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        logger.info("开始注入RmiInject.....");
       /* Iterator<String> it = beanFactory.getBeanNamesIterator();
       while (it.hasNext()){
           String beanName = it.next();
           Object object = beanFactory.getBean(beanName);
           Class clazz = beanFactory.getType(beanName);
           Field[] fields = clazz.getDeclaredFields();
           for (Field field : fields){
               RmiInject[] rmiInjects = field.getAnnotationsByType(RmiInject.class);
               if (rmiInjects == null || rmiInjects.length == 0){
                   continue;
               }
               if (rmiInjects.length > 1){
                   logger.error("RmiInject重复注解");
               }
               Class fieldClass = field.getType();
               if (fieldClass.getAnnotation(RmiServer.class) != null){
                    //初始化值
                   field.setAccessible(true);
                   try {
                       field.set(object,container.getProxyContainer().get(fieldClass.getSimpleName()));
                       logger.info("{}类的{}属性注入RmiInject",clazz.getSimpleName(), field.getName());
                   } catch (IllegalAccessException e) {
                       logger.error("RmiInject失败", e);
                   }
               }
           }*/
       //}

    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        this.beanFactory = (DefaultListableBeanFactory) beanFactory;
    }
}
